﻿namespace MobileTrack.Web.Controllers
{
    using System;
    using System.Collections.Generic;
    using System.Data.Entity;
    using System.Linq;
    using System.Web.Mvc;
    using System.Web.Security;
    using MobileTrack.Core.Data;
    using MobileTrack.Core.Model;
    using MobileTrack.Web.ViewModels;

    public class SeguimientosController : BaseController
    {
        public SeguimientosController(IRepositories repositories, MembershipProvider membershipProvider, RoleProvider roleProvider)
            : base(repositories, membershipProvider, roleProvider)
        {
        }

        public ActionResult Index(long? imei)
        {
            if (imei == null)
            {
                return this.RedirectToAction("Index", "Imeis");
            }

            var celular = this.Repositories
                .Celulares
                .All
                .Include(c => c.Seguimientos)
                .Single(c => c.Imei == imei);

            return this.View(new LastSeguimientoViewModel(celular));
        }

        public ActionResult GetAbonoId(long segId)
        {
            var venta = this.Repositories
                .Ventas
                .All
                .Where(v => v.SeguimientoId == segId)
                .FirstOrDefault();

            if (venta != null)
            {
                return this.Json(new { abonoId = venta.AbonoId }, JsonRequestBehavior.AllowGet);
            }
            else
            {
                return this.Json(new { abonoId = string.Empty }, JsonRequestBehavior.AllowGet);
            }
        }

        public ActionResult List(long imei, int page, int rows)
        {
            var celular = this.Repositories
                .Celulares
                .All
                .Include(c => c.Seguimientos)
                .SingleOrDefault(c => c.Imei == imei);

            var query = new List<Seguimiento>();

            if (celular != null)
            {
                query = celular.Seguimientos.OrderBy(s => s.Fecha).ThenBy(s => s.Id).ToList();
            }

            int totalRows = query.Count();
            int totalPages = (totalRows == 0) ? 1 : (int)Math.Ceiling((double)totalRows / (double)rows);
            page = (page < 1) ? 1 : page;

            var seguimientos = query
                .Skip((page - 1) * rows)
                .Take(rows)
                .ToArray()
                .Select(s => new SeguimientoViewModel(s, this.Repositories.Ventas.All.Where(v => v.SeguimientoId == s.Id).FirstOrDefault()));

            return this.Json(new { total = totalPages, page = page, records = totalRows, rows = seguimientos }, JsonRequestBehavior.AllowGet);
        }
    }
}
